package de.le.mfw.client.main.view.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;

public class TabSetWithPermission extends TabSet {

	public enum Permission {
		None(0), LoggedIn(1), Manager(2), Admin(3);

		private final int rank;

		Permission(int rank) {
			this.rank = rank;
		}

		public boolean equalOrMore(Permission otherPermission) {
			return rank >= otherPermission.rank;
		}
	}

	private Permission userRole = Permission.None;
	private List<Tab> addedTabs = new ArrayList<Tab>();
	private Map<Tab, Permission> tabs = new java.util.HashMap<Tab, TabSetWithPermission.Permission>();

	public void setUserRole(Permission userRole) {
		if (this.userRole != userRole) {
			boolean isMore = userRole.equalOrMore(this.userRole);
			this.userRole = userRole;

			if (isMore) {
				addTabsIfAutorized(userRole);
			} else {
				removeTabsIfNotAutorized(userRole);
			}
		}
	}

	private void removeTabsIfNotAutorized(Permission userRole) {
		for (Tab tab : new ArrayList<Tab>(addedTabs)) {
			if (!userRole.equalOrMore(tabs.get(tab))) {
				if (getSelectedTab().equals(tab)) {
					selectTab(0);
				}
				addedTabs.remove(tab);
				super.removeTab(tab);
			}
		}
	}

	private void addTabsIfAutorized(Permission userRole) {
		for (Tab tab : tabs.keySet()) {
			if (userRole.equalOrMore(tabs.get(tab)) && !addedTabs.contains(tab)) {
				addedTabs.add(tab);
				super.addTab(tab);
			}
		}
	}

	@Override
	public void addTab(Tab tab) {
		addTab(tab, Permission.None);
	}

	public void addTab(Tab tab, Permission permission) {
		tabs.put(tab, permission);

		if (userRole.equalOrMore(tabs.get(tab))) {
			addedTabs.add(tab);
			super.addTab(tab);
		}
	}
}
